﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace trunk.Views
{
    public partial class TcpIpClientWindow : Window
    {
        private TcpClient _tcpClient;
        private Task _receivingTask;
        private bool _isConnected;

        public TcpIpClientWindow()
        {
            InitializeComponent();
        }

        private async void StartConnectionButton_Click(object sender, RoutedEventArgs e)
        {
            if (!_isConnected)
            {
                try
                {
                    _tcpClient = new TcpClient();
                    await _tcpClient.ConnectAsync(IPAddress.Loopback, 8888);

                    _isConnected = true;
                    _receivingTask = Task.Run(ReceiveMessages);

                    MessageBox.Show("已连接到服务器。");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"连接服务器时出错: {ex.Message}");
                }
            }
        }

        private async Task ReceiveMessages()
        {
            try
            {
                NetworkStream stream = _tcpClient.GetStream();
                byte[] buffer = new byte[1024];
                while (_isConnected)
                {
                    int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
                    if (bytesRead == 0)
                    {
                        // 服务器断开连接
                        Dispatcher.Invoke(() =>
                        {
                            _isConnected = false;
                            MessageBox.Show("服务器断开连接。");
                            MessageListBox.Items.Clear();
                        });
                        break;
                    }
                    string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                    Dispatcher.Invoke(() =>
                    {
                        MessageListBox.Items.Add(message);
                    });
                }
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(() =>
                {
                    _isConnected = false;
                    MessageBox.Show($"接收消息时出错: {ex.Message}");
                    MessageListBox.Items.Clear();
                });
            }
        }

        private async void DisconnectButton_Click(object sender, RoutedEventArgs e)
        {
            if (_isConnected)
            {
                try
                {
                    _isConnected = false;
                    _tcpClient.Close();

                    if (_receivingTask != null)
                    {
                        await _receivingTask;
                    }

                    MessageListBox.Items.Clear();

                    MessageBox.Show("已断开与服务器的连接。");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"断开连接时出错: {ex.Message}");
                }
            }
        }

        private void SendToServerButton_Click(object sender, RoutedEventArgs e)
        {
            if (_isConnected)
            {
                try
                {
                    string message = InputTextBox.Text;
                    NetworkStream stream = _tcpClient.GetStream();
                    byte[] data = Encoding.UTF8.GetBytes(message);
                    stream.Write(data, 0, data.Length);

                    MessageListBox.Items.Add($"发送: {message}");
                    InputTextBox.Text = "";
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发送消息时出错: {ex.Message}");
                }
            }
        }
    }
}